using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.Scheduled;
using IM.Easy.ScheduledServices.Dtos;
using IM.Easy.ScheduledServices.IServices;
using Mapster;

namespace IM.Easy.ScheduledServices.Services
{
    public class JobExecutionHistoryService : AppServices<JobExecutionHistory>, IJobExecutionHistoryService
    {

        public JobExecutionHistoryService(ISqlSugarClient db) : base(db)
        {

        }

        public JobExecutionHistory Create(JobExecutionHistory entity)
        {
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public JobExecutionHistory GetById(Guid id)
        {
            return Context.Queryable<JobExecutionHistory>().InSingle(id);
        }

        public PageResponse<JobExecutionHistoryDto> GetPageList(JobExecutionHistoryQueryDto query)
        {
            var queryable = Context.Queryable<JobExecutionHistory>();
            var exp = Expressionable.Create<JobExecutionHistory>();
            exp = exp.AndIF(!string.IsNullOrEmpty(query.JobName), s => s.Job.Name.Contains(query.JobName))
                .AndIF(query.Success != default, s => s.Success == query.Success);
            var page = queryable
                 .IncludeInnerJoin(s => s.Job)
                 .Includes(s => s.Job.ToList(x => new ScheduledJob
                 {
                     Name = x.Name,
                     Id = x.Id,
                 }))
                 .Where(exp.ToExpression())
                 .ToPageList<JobExecutionHistory, JobExecutionHistoryDto>(query);
            return page;
        }

        public bool Delete(params Guid[] HistoryId)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<JobExecutionHistory>(HistoryId).ExecuteCommandHasChange();
        }
    }
}
